package servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.entity.Modelo;
import models.entity.Vehiculo;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet to handle File upload request from Client
 * @author Javin Paul
 */
public class FileUploadHandler extends HttpServlet {
    public static String UPLOAD_DIRECTORY = "C:/uploads";
  
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
      
        //process only if its multipart content
        if(ServletFileUpload.isMultipartContent(request)){
            try {
                File dir = new File(UPLOAD_DIRECTORY);
                if(!dir.exists()){
                    dir.mkdirs();
                }
                String patente = "";
                //OBTENER ARCHIVO
                List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                Vehiculo v = new Vehiculo();
                for(FileItem item : multiparts){
                    if(item.isFormField()){
                       
                        if(item.getFieldName().equals("patente")){
                            patente = item.getString();
                            v.setPatente(item.getString());
                        }else if(item.getFieldName().equals("modelo")){
                            Modelo m = new Modelo();
                            m.setId_modelo(Integer.parseInt(item.getString()));
                            v.setModelo(m);
                        }
                    }else{
                        item.write( new File(UPLOAD_DIRECTORY + File.separator + patente +".jpg"));
                    }
                }           
                //***** GUARDAR VEHICULO EN BASE DE DATOS ***** 
                
                //VOLVEMOS A PAGINA DE VEHICULOS
                response.sendRedirect(request.getContextPath()+"/catalogo/listaVehiculo.jsp");
              
            } catch (Exception ex) {
               request.setAttribute("message", "File Upload Failed due to " + ex);
            }   
        }else{
            //pagina de error al guardar
            response.sendRedirect(request.getContextPath()+"/catalogo/listaVehiculo.jsp");
        }
    
        
     
    }
  
}

